import React from 'react';
import { useDownload, DownloadItem } from './DownloadContext';
import {
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  LinearProgress,
  Typography,
  Box,
  Paper,
  Container,
} from '@mui/material';
import {
  Pause as PauseIcon,
  PlayArrow as PlayArrowIcon,
  Delete as DeleteIcon,
  Error as ErrorIcon,
} from '@mui/icons-material';

const formatSize = (bytes: number): string => {
  const sizes = ['B', 'KB', 'MB', 'GB'];
  let i = 0;
  let size = bytes;
  while (size >= 1024 && i < sizes.length - 1) {
    size /= 1024;
    i++;
  }
  return `${size.toFixed(2)} ${sizes[i]}`;
};

const formatSpeed = (bytesPerSecond: number): string => {
  if (bytesPerSecond === 0) return '0 KB/s';
  return `${formatSize(bytesPerSecond)}/s`;
};

const formatTimeRemaining = (seconds: number): string => {
  if (seconds === 0) return '';
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  }
  return `${minutes}分钟`;
};

const DownloadList: React.FC = () => {
  const { downloads, pauseDownload, resumeDownload, removeDownload } = useDownload();

  const renderDownloadStatus = (download: DownloadItem) => {
    switch (download.status) {
      case 'downloading':
        return (
          <Typography variant="body2" color="primary">
            {formatSpeed(download.speed)} - 剩余 {formatTimeRemaining(download.timeRemaining)}
          </Typography>
        );
      case 'completed':
        return (
          <Typography variant="body2" color="success.main">
            已完成
          </Typography>
        );
      case 'paused':
        return (
          <Typography variant="body2" color="warning.main">
            已暂停
          </Typography>
        );
      case 'error':
        return (
          <Typography variant="body2" color="error">
            {download.error || '下载出错'}
          </Typography>
        );
      default:
        return null;
    }
  };

  return (
    <Container maxWidth="md" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" sx={{ fontWeight: 'bold', color: 'primary.main' }}>
          下载管理
        </Typography>
      </Box>
      <Paper elevation={3} sx={{ borderRadius: 2, overflow: 'hidden' }}>
        <List>
          {downloads.map((download) => (
            <ListItem 
              key={download.id} 
              divider 
              sx={{
                py: 2,
                '&:hover': {
                  bgcolor: 'action.hover',
                },
                transition: 'background-color 0.2s',
              }}
            >
              <ListItemText
                sx={{ pr: 12 }}
                primary={
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    {download.status === 'error' && (
                      <ErrorIcon color="error" sx={{ mr: 1 }} />
                    )}
                    <Typography>{download.title}</Typography>
                  </Box>
                }
                secondary={
                  <Box sx={{ width: '100%', mt: 1 }}>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                      <Typography variant="body2">
                        {formatSize(download.size * (download.progress / 100))} / {formatSize(download.size)}
                      </Typography>
                      {renderDownloadStatus(download)}
                    </Box>
                    <LinearProgress
                      variant="determinate"
                      value={download.progress}
                      color={
                        download.status === 'error' ? 'error' :
                        download.status === 'completed' ? 'success' :
                        download.status === 'paused' ? 'warning' : 'primary'
                      }
                      sx={{
                        height: 8,
                        borderRadius: 4,
                        bgcolor: 'grey.200',
                        '& .MuiLinearProgress-bar': {
                          borderRadius: 4,
                        },
                      }}
                    />
                  </Box>
                }
              />
              <ListItemSecondaryAction sx={{ right: 16, display: 'flex', alignItems: 'center' }}>
                {download.status !== 'completed' && download.status !== 'error' && (
                  <IconButton
                    edge="end"
                    onClick={() =>
                      download.status === 'downloading'
                        ? pauseDownload(download.id)
                        : resumeDownload(download.id)
                    }
                    sx={{
                      '&:hover': {
                        color: 'primary.main',
                        bgcolor: 'primary.light',
                      },
                    }}
                  >
                    {download.status === 'downloading' ? <PauseIcon /> : <PlayArrowIcon />}
                  </IconButton>
                )}
                <IconButton
                  edge="end"
                  onClick={() => removeDownload(download.id)}
                  sx={{ 
                    ml: 1,
                    '&:hover': {
                      color: 'error.main',
                      bgcolor: 'error.light',
                    },
                  }}
                >
                  <DeleteIcon />
                </IconButton>
              </ListItemSecondaryAction>
            </ListItem>
          ))}
        </List>
      </Paper>
    </Container>
  );
};

export default DownloadList;